<!DOCTYPE html>
<html xmlns:th="http://www.w3.org/1999/xhtml" xmlns:v-bind="http://www.w3.org/1999/xhtml"
      xmlns:v-on="http://www.w3.org/1999/xhtml">
<head>
    <title>Checkout</title>
    <!-- for-mobile-apps -->
    <meta name="viewport" content="width=device-width, initial-scale=1"/>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <meta name="keywords" content="Best Store Responsive web template, Bootstrap Web Templates, Flat Web Templates, Android Compatible web template,
Smartphone Compatible web template, free webdesigns for Nokia, Samsung, LG, SonyEricsson, Motorola web design"/>
    <div th:include="css :: css"></div>
    <!-- //animation-effect -->
    <style>
        .checkout-right-basket {
            float: right;
            margin: 2em 0 0 0em !important;
        }
    </style>
    <script src="https://cdn.bootcss.com/layer/3.0.3/layer.min.js"></script>
</head>

<body>



<!-- header -->
<div th:include="/header :: header"></div>
<!-- //header -->
<!-- breadcrumbs -->
<div class="breadcrumbs">
    <div class="container">
        <ol class="breadcrumb breadcrumb1 animated wow slideInLeft" data-wow-delay=".5s">
            <li><a href="index.html"><span class="glyphicon glyphicon-home" aria-hidden="true"></span>主页</a></li>
            <li class="active">购物车</li>
        </ol>
    </div>
</div>
<!-- //breadcrumbs -->
<!-- checkout -->
<div class="checkout" id="content">

    <!-- 模态框（Modal） -->
    <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
                        &times;
                    </button>
                    <h4 class="modal-title" id="myModalLabel">
                        地址添加
                    </h4>
                </div>
                <div class="modal-body">
                    <div class="form-group">
                        <label class="col-sm-2 control-label">省份</label>
                        <div class="col-sm-10">
                            <input type="text" v-model="adaddress.province" class="form-control"
                                   placeholder="请输入省份">
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">市</label>
                        <div class="col-sm-10">
                            <input type="text" v-model="adaddress.city" class="form-control"
                                   placeholder="请输入市">
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">区或县</label>
                        <div class="col-sm-10">
                            <input type="text" v-model="adaddress.county"  class="form-control"
                                   placeholder="请输入区或县">
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">描述</label>
                        <div class="col-sm-10">
                            <input type="text" v-model="adaddress.detail"  class="form-control"
                                   placeholder="请输入描述">
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭
                    </button>
                    <button type="button" onclick="addaddress()" class="btn btn-primary">
                        确认添加
                    </button>
                </div>
            </div><!-- /.modal-content -->
        </div><!-- /.modal -->
    </div>



    <div class="container">
        <h3 class="animated wow slideInLeft" data-wow-delay=".5s">你的购物车商品数量: <span>{{cartlist.length}}</span></h3>
        <div class="checkout-right animated wow slideInUp" data-wow-delay=".5s">
            <table class="timetable_sub">
                <thead>
                <tr>
                    <th>id</th>
                    <th>商品图</th>
                    <th>数量</th>
                    <th>商品名字</th>
                    <th>单价</th>
                    <th>价格</th>
                    <th>移除</th>
                </tr>
                </thead>
                <tr class="rem1" v-for="(item, index) in cartlist">
                    <td class="invert">{{item.id}}</td>
                    <td class="invert-image"><img v-bind:src="item.goods.prc" width="100px" alt=" "
                                                  class="img-responsive"/></td>
                    <td class="invert">
                        <div class="quantity">
                            <div class="quantity-select">
                                <div v-on:click="jian(item)" class="entry value-minus">&nbsp;</div>
                                <div class="entry value"><span>{{item.num}}</span></div>
                                <div v-on:click="jia(item)" class="entry value-plus active">&nbsp;</div>
                            </div>
                        </div>
                    </td>
                    <td class="invert">{{item.goods.name}}</td>
                    <td class="invert">${{item.goods.price}}</td>
                    <td class="invert">${{(item.num)*(item.goods.price)}}</td>
                    <td class="invert">
                        <div class="rem">
                            <div v-on:click="remove(item, index)" class="close1"></div>
                        </div>

                    </td>
                </tr>


            </table>
        </div>
        <div class="checkout-left">
            <div class="checkout-left-basket animated wow slideInLeft" data-wow-delay=".5s">
                <h4>购物单</h4>
                <ul>
                    <li v-for="item in cartlist">{{item.goods.name}} <i>-</i>
                        <span>${{(item.num)*(item.goods.price)}} </span></li>
                    <li>总价 <i>-</i> <span>${{sumnum}}</span></li>
                </ul>

            </div>
            <div class="checkout-right-basket animated wow slideInRight" data-wow-delay=".5s">
                    <div class="form-group">
                        <label>选择地址</label>
                        <select class="form-control" v-model="addressid">
                            <option v-for="item in addresslist" v-bind:value="item.id" >{{item.province}}-{{item.city}}-{{item.county}}</option>
                        </select>
                    </div>
                    <button class="btn btn-default btn-lg" data-toggle="modal" data-target="#myModal">
                        添加新地址
                    </button>
                    <br><br><br>

                <a href="#" v-on:click="sub()"><span class="glyphicon glyphicon-menu-left" aria-hidden="true"></span>去购买</a>
            </div>
            <div class="clearfix"></div>
        </div>
    </div>
</div>
<!-- //checkout -->

<!-- footer -->
<div class="footer">
    <div class="container">
        <div class="footer-logo animated wow slideInUp" data-wow-delay=".5s">
            <h2><a href="index.html">易购网<span>你得贴心小窝</span></a></h2>
        </div>
        <div class="copy-right animated wow slideInUp" data-wow-delay=".5s">
            <p>Copyright &copy; 2018</p>
        </div>
    </div>
</div>
<!-- //footer -->
<!--quantity-->
<script>
    $('.close1').on('click', function (c) {
        $('.rem1').fadeOut('slow', function (c) {
            $('.rem1').remove();
        });
    });
    $('.value-plus').on('click', function () {
        var divUpd = $(this).parent().find('.value'), newVal = parseInt(divUpd.text(), 10) + 1;
        divUpd.text(newVal);
    });

    $('.value-minus').on('click', function () {
        var divUpd = $(this).parent().find('.value'), newVal = parseInt(divUpd.text(), 10) - 1;
        if (newVal >= 1) divUpd.text(newVal);
    });
</script>
<!--quantity-->

<script>

    (function($) {
        // copy from jquery.js
        var r20 = /%20/g,
            rbracket = /\[\]$/;

        $.extend({
            customParam: function( a ) {
                var s = [],
                    add = function( key, value ) {
                        // If value is a function, invoke it and return its value
                        value = jQuery.isFunction( value ) ? value() : value;
                        s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
                    };

                // If an array was passed in, assume that it is an array of form elements.
                if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
                    // Serialize the form elements
                    jQuery.each( a, function() {
                        add( this.name, this.value );
                    });

                } else {
                    for ( var prefix in a ) {
                        buildParams( prefix, a[ prefix ], add );
                    }
                }

                // Return the resulting serialization
                return s.join( "&" ).replace( r20, "+" );
            }
        });

        /* private method*/
        function buildParams( prefix, obj, add ) {
            if ( jQuery.isArray( obj ) ) {
                // Serialize array item.
                jQuery.each( obj, function( i, v ) {
                    if (rbracket.test( prefix ) ) {
                        // Treat each array item as a scalar.
                        add( prefix, v );

                    } else {
                        buildParams( prefix + "[" + ( typeof v === "object" || jQuery.isArray(v) ? i : "" ) + "]", v, add );
                    }
                });

            } else if (obj != null && typeof obj === "object" ) {
                // Serialize object item.
                for ( var name in obj ) {
                    buildParams( prefix + "." + name, obj[ name ], add );
                }

            } else {
                // Serialize scalar item.
                add( prefix, obj );
            }
        };
    })(jQuery);
</script>

<script>

    var vm = new Vue({
        el: '#content',
        data: {
            cartlist: null,
            addresslist:null,
            adaddress:{
                province:'',
                city:'',
                county:'',
                detail:'',
                user_id:localStorage.shopuserid
            },
            addressid:null
        },
        methods: {
            gotosingle: function (id) {
                // 方法内 `this` 指向 vm
                gotosingle(id);
                this.$options.methods.sum();
            },
            addcart: function (id) {
                // 方法内 `this` 指向 vm
                addcart(id, 1);
                this.$options.methods.sum();
            },
            findgoods: function (id) {
                findgoods(id);
                this.$options.methods.sum();
            },
            jian: function (item) {
                if (item.num == 0) {

                } else {
                    item.num--;
                }
                this.sum();
            },
            jia: function (item) {
                if (item.num == item.goods.stock) {

                } else {
                    item.num++;
                }
                this.$options.methods.sum();
            },
            addddress: function (item) {

            },
            remove: function (item, index) {
                this.cartlist.splice(index, 1);
                $.ajax({
                    url: '/shoppingCart/find/delete',
                    data: {
                        id: item.id
                    },
                    type: 'GET',
                })
                    .done(function (res) {
                        console.log(res)
                        console.log("success");
                    })
                    .fail(function () {
                        console.log("error");
                    })
                    .always(function () {
                        console.log("complete");
                    });
                this.$options.methods.sum();
            },
            sub: function () {
                console.log(this.addressid)
                if(this.addressid ==null){
                    alert("请选择地址")
                    return;
                }
                var orderItems = [];
                var to = 0;
                for (var i = 0; i < this.cartlist.length; i++) {
                    var item = {};
                    item.goods = this.cartlist[i].goods;
                    item.price = this.cartlist[i].goods.price;
                    item.num = this.cartlist[i].num;
                    item.totalPrice = item.price * item.num;
                    item.comment = false;
                    item.refund = 0;
                    to += item.totalPrice;
                    orderItems.push(item);
                }
                
                $.ajax({
                    url: '/order/add',
                    data: $.customParam({
                            'totalPrice' : to,
                            'orderItems': orderItems
                            ,'address': {
                                'id': this.addressid
                            }
                    }),
                    type: 'POST',
                })
                    .done(function (res) {
                        console.log(res)
                        if (res.code==1001){

                            localStorage.orderid=res.obj.id;
                            window.location.href="/orderdetails"
                        }else{
                            alert("有错误！")
                        }
                        console.log("success");
                    })
                    .fail(function () {
                        console.log("error");
                    })
                    .always(function () {
                        console.log("complete");
                    });
                for (var i = 0 ; i < this.cartlist.length; i++) {
                    this.remove(this.cartlist[i], i);
                }
                this.$options.methods.sum();
            }
        }
        ,
        computed: {
            // 计算属性的 getter
            sumnum: function () {
                // `this` 指向 vm 实例
                var sum=0;
                for (var i=0 ;i<this.cartlist.length;i++){
                    console.log("asdfas")
                    sum=sum+((this.cartlist[i].num)*(this.cartlist[i].goods.price))
                }
                return sum
            }
        }
    })

    function addaddress(){
        console.log(vm.adaddress);
        $.ajax({
            url: '/address/add',
            data: vm.adaddress,
            type: 'POST',
        }).done(function (res) {
                console.log(res)
                if(res.code==1001){
                    alert("添加成功");
                    init();
                    $('#myModal').modal('hide')
                }else{
                    alert("添加失败")
                }
                console.log("地址：success");
            })
            .fail(function () {
                console.log("error");
            })
            .always(function () {
                console.log("complete");
            });
        $('#myModal').modal('hide')
    }

    init();
function init(){
    $.ajax({
        url: '/address/find/user',
        type: 'GET',
    }).done(function (res) {
        console.log(res.obj)
        vm.addresslist = res.obj
        console.log("地址success");
    })
        .fail(function () {
            console.log("error");
        })
        .always(function () {
            console.log("complete");
        });
}

    $.ajax({
        url: '/shoppingCart/find/car/all',
        type: 'GET',
    }).done(function (res) {
        console.log(res.obj)
        vm.cartlist = res.obj
        console.log("success");
    })
        .fail(function () {
            console.log("error");
        })
        .always(function () {
            console.log("complete");
        });

</script>
</body>
</html>